<template>
  <view class="container" :style="appThemeStyle">
    <mescroll-body ref="mescrollRef" :sticky="true" @init="mescrollInit" :down="{ use: false }" :up="upOption"
      @up="upCallback">
      <!-- tab栏 -->
      <u-tabs :list="tabs" :is-scroll="false" v-model="curTab" :active-color="appTheme.mainBg" :duration="0.2"
        @change="onChangeTab"/>
		<view class="log-list">
		  <view v-for="(item, index) in list.data" :key="index" class="log-item">
		    <view class="item-left flex-box">
		      <view class="rec-status">
		        <text>{{ item.type_name }}<text style="color: gray">【来源：{{item.from_mobile}}({{item.from_nick_name}})，备注：{{item.remark}}{{item.out_trade_no}}】</text></text>
			 </view>
		      <view class="rec-time">
		        <text>{{ item.created_at }}</text>
		      </view>
		    </view>
		    <view class="item-right">
		      <text>{{ item.amount > 0 ? '+' : '' }}{{ item.amount }}元</text>
		    </view>
		  </view>
		</view>
    </mescroll-body>
  </view>
</template>

<script>
  import MescrollMixin from '@/uni_modules/mescroll-uni/components/mescroll-uni/mescroll-mixins'
  import { getEmptyPaginateObj, getMoreListData } from '@/core/app'
  import * as UserApi from '@/api/user'
  import { CouponTypeEnum } from '@/common/enum/coupon'
	import storage from '@/utils/storage'

  const color = ['red', 'blue', 'violet', 'yellow']
  const pageSize = 15
  const tabs = [{
    name: `全部`,
    value: ['all']
  }, {
    name: `可用`,
    value: ['active','4']
  }, {
    name: `预估`,
    value: ['freeze']
  }]
  
  export default {
    mixins: [MescrollMixin],
    data() {
      return {
        // 枚举类
        CouponTypeEnum,
        // 颜色组
        color,
        // 标签栏数据
        tabs,
        // 当前标签索引
        curTab: 0,
        // 列表数据
        list: getEmptyPaginateObj(),
        // 上拉加载配置
        upOption: {
          // 首次自动执行
          auto: true,
          // 每页数据的数量; 默认10
          page: { size: pageSize },
          // 数量要大于4条才显示无更多数据
          noMoreSize: 4,
          // 空布局
          empty: {
            tip: '亲，暂无相关数据'
          }
        },
		type:'all',
		remark:'',
		title:''
      }
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
		// console.log(options.type=="active")
		if(typeof options.type !== 'undefined'){
			if(tabs[2].value.includes(options.type)){
				this.curTab = 2
			}else if(tabs[1].value.includes(options.type)){
				this.curTab = 1
			}
			this.type = options.type
		}
		
		if(typeof options.remark !== 'undefined'){
			this.remark = options.remark
		}
		
		if(typeof options.remark !== 'undefined' && options.remark=='agent'){
			const pages = getCurrentPages();
			const currentPage = pages[pages.length - 1];
			// #ifndef APP-PLUS
			this.title = currentPage.$page.meta.navigationBar.titleText;
			// #endif
				 
			// #ifdef APP-PLUS
			let webView = currentPage.$getAppWebview();
			this.title = webView.getStyle().name;
			// #endif
			
			// 设置当前页面标题
			uni.setNavigationBarTitle({ title:'代理'+this.title})
		}
    },
    methods: {

      /**
       * 上拉加载的回调 (页面初始化时也会执行一次)
       * 其中page.num:当前页 从1开始, page.size:每页数据条数,默认10
       * @param {Object} page
       */
      upCallback(page) {
        const app = this
        // 设置列表数据
        app.getCouponList(page.num)
          .then(list => {
            const curPageLen = list.data.length
            const totalSize = list.data.total
            app.mescroll.endBySize(curPageLen, totalSize)
          })
          .catch(() => app.mescroll.endErr())
      },

      /**
       * 获取优惠券列表
       */
      getCouponList(pageNo = 1) {
        const app = this
		// 保存推荐人ID到缓存
		let refereeId = storage.get('userId')
		if(app.recUserId){
			refereeId = this.recUserId
		}
		if(!refereeId){
			app.$toast('推荐人不存在，请先登录');return
		}
        return new Promise((resolve, reject) => {
          UserApi.decCoinFlow({ type: app.getTabValue(),remark:app.remark,userId:refereeId, page: pageNo }, { load: false })
            .then(result => {
              // 合并新数据
              const newList = result.data.list
              app.list.data = getMoreListData(newList, app.list, pageNo)
              resolve(newList)
            })
        })
      },

      // 数据类型
      getTabValue() {
		  let value = this.tabs[this.curTab].value
		  if(value.includes(this.type)){
		  	return this.type
		  }else {
		  	return value[0]
		  }
      },

      // 切换标签项
      onChangeTab(index) {
        const app = this
        // 设置当前选中的标签
        app.curTab = index
        // 刷新列表
        app.onRefreshList()
      },

      // 刷新优惠券列表
      onRefreshList() {
        this.list = getEmptyPaginateObj()
        setTimeout(() => {
          this.mescroll.resetUpScroll()
        }, 120)
      },

    }
  }
</script>

<style lang="scss" scoped>
  page,
  .container {
    background: #fff;
  }

  .log-list {
    padding: 0 30rpx;
  }

  .log-item {
    font-size: 28rpx;
    padding: 20rpx 20rpx;
    line-height: 1.8;
    border-bottom: 1rpx solid rgb(238, 238, 238);
    display: flex;
    justify-content: center;
    align-items: center;
  }

  .rec-status {
    color: #333;

    .rec-time {
      color: rgb(160, 160, 160);
      font-size: 26rpx;
    }
  }
</style>
